package com.eyolas.passwordmanager.dao;

import java.sql.SQLException;
import java.util.List;
import java.util.ListIterator;
import android.util.Log;

import com.eyolas.passwordmanager.idao.ICategoryDao;
import com.eyolas.passwordmanager.model.Category;
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.support.ConnectionSource;

/**
 * Category Dao
 * @author Eyolas
 * @date 24 mai 2012
 */
public class CategoryDao extends BaseDaoImpl<Category, Integer> implements ICategoryDao{
	public CategoryDao(ConnectionSource connectionSource) throws SQLException {
		super(connectionSource, Category.class);
	}

	@Override
	public List<Category> getAllByOrderName() throws SQLException {
		List<Category> listCategory = queryBuilder().orderByRaw("cat_name COLLATE NOCASE").query();
		if (listCategory != null) {
			ListIterator<Category> i = listCategory.listIterator();
			while (i.hasNext()) {
				Category current = i.next();
				current.setNbAccount(getNbAccount(current));
				i.set(current);
			}
		}
		return listCategory;
	}
	
	@Override
	public int getNbAccount(Category category) {
		GenericRawResults<String[]> rawResult;
		try {
			rawResult = queryRaw("SELECT count(*) as nb from t_account_acc where acc_category = " + category.getId());
			return Integer.valueOf(rawResult.getResults().get(0)[0]);
		} catch (Exception e) {
			Log.e(CategoryDao.class.getName(), "error : " + e);
			return 0;
		}
	}

	@Override
	public boolean categoryExist(String name) throws SQLException {
		QueryBuilder<Category, Integer> queryBuilder = queryBuilder();
		queryBuilder.setCountOf(true);
		long result = countOf(queryBuilder.where().eq("cat_name", name).prepare());
		return result > 0;
	}
}
